package com.park.web.controller.pub;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.park.client.model.log.LoginLogModel;
import com.park.client.model.pub.ProtocolModel;
import com.park.client.model.user.UserModel;
import com.park.client.model.user.UserMsgModel;
import com.park.client.service.log.LoginLogService;
import com.park.client.service.pub.ProtocolService;
import com.park.client.service.user.UserMsgService;
import com.park.client.service.user.UserService;
import com.park.common.constant.Constant;
import com.park.common.empty.EmptyUtils;
import com.park.common.file.ImageUtil;
import com.park.common.util.MD5;
import com.park.common.util.Result;
import com.park.web.contant.Global;
import com.park.web.controller.BaseController;
import com.park.web.enums.CheckTypeEnum;
import com.park.web.util.IPUtil;
import com.park.web.util.SessionUtil;
import com.park.web.util.email.EmailUtil;

@Controller
@RequestMapping("/public/user")
public class PublicUserController extends BaseController{

	@Autowired
	private UserService userService;
	@Autowired
	private LoginLogService loginLogService;
	@Autowired
	private ProtocolService protocolService;
	@Autowired
	private UserMsgService userMsgService;
	/**
	 * 显示图片
	 */
	@RequestMapping("showPicture/{id}")
	public void showPicture(@PathVariable("id")Long id,HttpServletResponse response) throws IOException{
			UserModel user =	userService.selectByPrimaryKey(id);
			if(user == null){
				return;
			}
			byte[] data = user.getPicture();
			ImageUtil.writeToPicture(data, response);
	}
	
	/**
	 * 跳转到登陆页面
	 */
	@RequestMapping("/login")
	public String login(){
		return Global.PUBLIC_PATH+"login";
	}
	
	
	/**
	 * 注册成功页面
	 */
	@RequestMapping("/registerSuccess")
	public String registerSuccess(){
		return Global.PUBLIC_PATH+"registerSuccess";
	}
	
	/**
	 * 注册页面
	 */
	@RequestMapping("register")
	public String register(HttpServletRequest request){
		ProtocolModel protocol = protocolService.selectLatestProtocol();
		request.setAttribute("protocol", protocol);
		return Global.PUBLIC_PATH+"user/register";
	} 
	
	/**
	 * 实现注册功能
	 */
	@RequestMapping("registerUser")
	@ResponseBody
	public Result<Boolean> registerUser(UserModel user,HttpSession session,HttpServletRequest request){
		Result<Boolean> result = new Result<>(false);
		try {
			//检查用户名是否存在
			user.setCheckType(CheckTypeEnum.USERNAME.code);
			UserModel u = userService.registerCheck(user);
			if(u != null){
				result.setMessage("该帐号已被注册,请换一个试试!");
				return result;
			}
			
			user.setCheckType(CheckTypeEnum.EMAIL.code);
			u = userService.registerCheck(user);
			if(u != null){
				result.setMessage("该邮箱已存在,请换一个试试!");
				return result;
			}
			
			user.setIp(IPUtil.getIP(request));
			result = this.userService.registerUser(user);//保存
			if(!result.isSuccess()){
				//发送注册消息
				saveMsg(user);
				sendEmailMsg(user, request);
			}else{
				result.setMessage("很遗憾,注册失败,再来一次吧!");
				result.setSuccess(false);
				return result;
			}
		} catch (Exception e) {
			logger.error("账号{}注册失败{}",user.getUsername(),e);
			result.setMessage("很遗憾,注册失败,再来一次吧!");
			result.setSuccess(false);
			return result;
		}
		result.setSuccess(true);
		return result;
	}
	
	
	/**
	 * 注册成功发送消息
	 */
	private void saveMsg(UserModel user){
		UserMsgModel msg = new UserMsgModel();
		msg.setMsgTitle(Constant.SUCCESS_REGISTER_TITLE);
		msg.setMsgContent(Constant.SUCCESS_REGISTER_CONTENT);
		msg.setCreater(Constant.USER_TYPE_ID);
		userMsgService.saveMsg(msg,user.getId());
	}
	
	/**
	 * 注册激活邮件
	 */
	private void sendEmailMsg(UserModel user,HttpServletRequest request){
		StringBuilder builder = new StringBuilder("http://");
		builder.append(request.getServerName())//服务器地址 
		.append(":")
		.append(request.getServerPort())//端口号  
		.append(request.getContextPath());//项目名称 
		StringBuilder urBuilder = new StringBuilder("<a href=\"");
		urBuilder.append(Constant.BASEPATH)
		.append("/public/user/registerActivate?username=")
		.append(user.getUsername())
		.append("")
		.append(" target=\"_black\">立即激活</a>,如果此处打不开，请将以下地址复制到浏览器中:")
		.append(Constant.BASEPATH)
		.append("/public/user/registerActivate?username=")
		.append(user.getUsername());
		EmailUtil.sendEmail(Constant.EMAIL_SUBJECT,user.getEmail(),urBuilder.toString());
	}
	
	/**
	 *注册成功发送邮件激活页面，并检验邮箱是否可用
	 */
	@RequestMapping("registerActivate")
	public String registerActivate(String username,HttpServletRequest request){
		request.setAttribute("username",username);
		return Global.PUBLIC_PATH+"user/registerActivate";
	}
	
	/**
	 *发送邮件激活，更改状态
	 */
	@RequestMapping("registerActivateStatus")
	@ResponseBody
	public Result<Boolean> registerActivateStatus(String username){
		Result<Boolean> result = new Result<>();
		UserModel u = userService.login(username);
		u.setDisabled(Global.CODE_1);//激活状态
		boolean success =  userService.updateByPrimaryKey(u);
		if(success){
			result.setMessage("恭喜你,激活成功!");
			result.setSuccess(true);
		}else{
			result.setMessage("很遗憾,激活失败!");
			result.setSuccess(false);
		}
		return result;
	}
	
	/**
	 *找回密码页面
	 */
	@RequestMapping("forgetPassword")
	public String forgetPassword(){
		return Global.PUBLIC_PATH+"user/forgetPassword";
	}
	
	/**
	 * 登录验证
	 **/
	@RequestMapping("checkLogin")
	@ResponseBody
	public Result<Boolean> checkLogin(String username,String password,HttpServletRequest request,HttpServletResponse response){
		Result<Boolean> result = new Result<>(true);
		UserModel user = userService.login(username);
		if(user == null){//用户名不存在
			result.setSuccess(false);
			result.setMessage("用户名不存在!");
			result.setCode(-3);
			return result;
		}
		String pwd = MD5.md5(password);
		if(EmptyUtils.isEmpty(user.getPassword()) || !user.getPassword().equals(pwd)){
			result.setMessage("密码错误!");
			result.setCode(-2);
			result.setSuccess(false);
			return result;
		}
		String msg = "";
		boolean success = false;
		switch (user.getDisabled()) {
			case -1:
		 		msg = "账号未认证!";
		 		break;
		 	case 0:
		 		msg = "账号已被锁定!";
		 		break;
		 	case 1:
		 		success = true;
		 		msg = "登陆成功!";
		 		SessionUtil.putUserIntoSession(user);
		 		//写登录日志
		 		LoginLogModel loginLog = new LoginLogModel();
		 		loginLog.setCreater(user.getId());
		 		loginLog.setUsername(user.getUsername());
		 		loginLog.setCreateDate(new Date());
		 		loginLog.setIp(IPUtil.getIP(request));
		 		loginLogService.insertSelective(loginLog);
		 		break;
		 	case 2:
		 		msg = "你的账号还未激活,请进邮箱查看激活地址!";
		 		break;
		 	default:
		 	break;
		}
		result.setSuccess(success);
		result.setMessage(msg);
		return result;
	}
	
	/**
	 *输入邮箱.发送邮件找回密码页面
	 */
	@RequestMapping("updatePwdSendEmail")
	@ResponseBody
	public Result<Boolean> updatePwdSendEmail(String username,String email,HttpServletRequest request){
		Result<Boolean> result = new Result<>(true);
		UserModel user = userService.selectByEmail(username);
		if(user == null){
			result.setMessage("很遗憾,你输入的用户名不正确!");
			result.setSuccess(false);
			return result;
		}
		
		if(!user.getEmail().equals(email)){
			result.setMessage("很遗憾,你输入的用户名和注册的邮箱不匹配不正确!");
			result.setSuccess(false);
			return result;
		}
		
		//生成密钥
		String secretKey=UUID.randomUUID().toString();
		String content = EmailUtil.emailContent(updateDate(user,secretKey),secretKey,request);
			boolean success = EmailUtil.sendEmail("修改密码", email, content);
			if(success){
				result.setMessage("恭喜你,修改密码邮件发送，请进入邮箱查看!");
			}else{
				result.setMessage("很遗憾,邮件发送失败!");
				result.setSuccess(false);
			}
		return result;
	}
	
	/**
	 * 设置过期日期和code
	 * @return
	 */
	public UserModel updateDate(UserModel u,String secretKey){
		//设置过期时间
		Date outDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);// 30分钟后过期
		u.setOutDate(outDate);
		String validataCode = MD5.md5(u.getUsername() +"$"+outDate+"$"+secretKey);
		u.setValidataCode(validataCode);
		userService.updateByPrimaryKeySelective(u);
		return u;
	}
}
